<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

// use Illuminate\Http\Request;
// use App\Models\Authorization;
// use App\Transformers\AuthorizationTransformer;

class VchanController extends BaseController
{
    // 数据库名称
    // private $dbname = "user_center";
    /**
     * 获取指定服务商指定频道的数据
     * @get("/{spid}/collists/")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": [error失败|success成功], message="返回信息|null",data": "null|返回数据"})
     */
    public function vchanMeta(Request $request, $spid, $termid, $vchanid)
    {
        // $termid = $request->header('device-token');
        if (empty($termid)) {
            return response()->json(['status' => '404', 'data' => '设备ID为空!']);
        }
        if (empty($spid)) {
            return response()->json(['status' => '404', 'data' => '服务商ID不能为空']);
        }
        if (empty($vchanid)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }

        $result = DB::table('vchans')->where(['vchan_id' => $vchanid])->first();
        if (empty($result)) {
            return response()->json(['status' => '404', 'data' => '没有找到此直播媒体资源!']);
        }
        DB::table('vchans')->where(['vchan_id' => $vchanid])->increment('page_view');
        // FTP配置
        $ftpUrl = config('app.host.ftp');
        // 返回浏览量
        $data['page_view'] = $result->page_view;
        // 直播ID
        $data['vchan_id'] = $result->vchan_id;
        // 标题
        $data['title'] = $result->title;
        // 副标题
        $data['subtitle'] = $result->subtitle;
        // 详情
        $data['long_desc'] = $result->long_desc;
        // 简述
        $data['short_desc'] = $result->short_desc;
        // 直播频道EPG
        $data['vepgs'] = $result->vepgs;
        // 直播频道流
        $data['vcstreams'] = $result->vcstreams;
        // $data['tags']      = $result->tags;
        $data['tags']  = explode('&', $result->tags);
        $data['vlogo'] = $ftpUrl . $result->vlogo;

        $data['img']        = json_decode(json_encode(['href' => $ftpUrl . $result->vlogo]));
        $data['start_time'] = strtotime($result->start_at);
        $data['end_time']   = strtotime($result->expiring_at);

        $data['spell'] = $result->spell;
        // 收费类型
        // $data['charge_type'] = $result->charge_type;
        // 海报
        $vcposters = json_decode($result->vcposters, 1);
        if (empty($vcposters)) {
            $data['vcposters'] = (object) [];
        } else {
            $vcposters[0]['href'] = $ftpUrl . $vcposters[0]['href'];

            $data['vcposters'] = $vcposters[0];
        }

        // 获取焦点事件
        $data['onclick']['route']["tplType"] = "";
        $data['onclick']['route']["tplID"]   = "";
        $data['onclick']['href']             = url("/{$spid}/{$termid}/vchan/{$vchanid}/media");

        $data['services']['play']['route'] = url("/{$spid}/{$termid}/vchan/{$vchanid}/media");
        $data['services']['play']['data']  = "";
        $data['services']['back']['route'] = "";
        $data['services']['back']['data']  = "";

        return response()->json(['status' => '200', 'data' => $data]);
    }
    /**
     * 获取指定服务商指定频道的播放数据,频道播放详情
     * @get("/{spid}/collists/")
     * @Versions({"v1"})
     * @Request()
     * @Response("status": [error失败|success成功], message="返回信息|null",data": "null|返回数据"})
     */
    public function vchanMedia($spid, $termid, $vchanid)
    {
        if (empty($termid)) {
            return response()->json(['status' => '404', 'data' => '设备ID为空!']);
        }

        if (empty($spid)) {
            return response()->json(['status' => '404', 'data' => '服务商ID不能为空']);
        }
        if (empty($vchanid)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }
        // FTP 配置
        $ftpUrl  = config('app.host.ftp');
        $results = DB::table('vchans')->where(['vchan_id' => $vchanid])->first();
        if (empty($results)) {
            return response()->json(['status' => '404', 'data' => '没有找到此媒体资源']);
        }
        // 视频的vid
        $data['vid']           = $vchanid;
        $data['async_content'] = json_decode($results->async_content);
        // 获取相关播放信息
        $source         = "瀚动";
        $data['source'] = $source;

        return response()->json(['status' => '200', 'data' => $data]);
    }

    /**
     * 获取直播媒资信息
     */
    public function v1VchanMeta(Request $request, $spid, $termid, $vchanid)
    {
        // $termid = $request->header('device-token');
        if (empty($termid)) {
            return response()->json(['status' => '404', 'data' => '设备ID为空!']);
        }
        if (empty($spid)) {
            return response()->json(['status' => '404', 'data' => '服务商ID不能为空']);
        }
        if (empty($vchanid)) {
            return response()->json(['status' => '404', 'data' => '媒资ID不能为空']);
        }

        $results = DB::table('vassetis')->where(['vasseti_id' => $vchanid])->first();
        if (empty($results)) {
            return response()->json(['status' => '404', 'data' => '没有找到此媒体资源!']);
        }
        DB::table('vassetis')->where(['vasseti_id' => $vchanid])->increment('page_view');
        // FTP配置
        $ftpUrl = config('app.host.ftp');
        // 返回浏览量
        $data['page_view'] = $results->page_view;
        // 直播ID
        $data['vchan_id'] = $results->vasseti_id;
        // 标题
        $data['title'] = $results->title;
        // 副标题
        $data['subtitle'] = $results->subtitle;
        // 评分
        $data['score'] = $results->score;
        // 详情
        $data['long_desc'] = $results->long_desc;
        // 简述
        $data['short_desc'] = $results->short_desc;
        // 集数
        $data['episode'] = $results->episode;

        // 分类
        $data['tags'] = DB::table('vasseti_vcattags')->where('vasseti_vcattags.vasseti_id', $vchanid)->join('vcattags', 'vasseti_vcattags.vcattag_id', '=', 'vcattags.vcattag_id')->pluck('vcattags.name')->implode(',', 'name');

        // 导演
        $data['directors'] = explode('&', $results->directors);
        // 演员
        $data['actors'] = explode('&', $results->actors);
        // 翻译
        $data['translator'] = explode('&', $results->directors);
        // 海报
        $posters = json_decode($results->posters, 1);
        if (empty($posters)) {
            $data['posters'] = (object) [];
        } else {
            $posters[0]['href'] = $ftpUrl . $posters[0]['href'];

            $data['posters'] = $posters[0];
        }
        // 图片
        $img = json_decode($results->imgs, 1);
        if (empty($img)) {
            $data['img'] = (object) [];
        } else {
            foreach ($img as $key => $value) {
                $imgHref = image_match($value['href'], 'BIMG');
                if ($imgHref) {
                    $data['img'] = json_decode(json_encode(['href' => $ftpUrl . $imgHref]));
                    break;
                } else {
                    $data['img'] = (object) [];
                }
            }
        }
        // 获取焦点事件
        $data['onclick']['route']["tplType"] = "";
        $data['onclick']['route']["tplID"]   = "";
        // $data['onclick']['href']             = url("/{$spid}/vasset/{$vassetid}/media");
        $data['onclick']['href'] = url("/{$spid}/{$termid}/vasset/{$vchanid}/media");

        $data['services']['play']['route'] = url("/{$spid}/{$termid}/vasset/{$vchanid}/media");
        $data['services']['play']['data']  = "";
        // 判断是否收藏
        if (DB::table('favorites')->where(['term_id' => $termid, 'vasseti_id' => $vchanid])->first()) {
            // 取消媒资收藏的链接
            $data['services']['unfavorite']['route'] = url("/{$spid}/ugc/unfavorite/{$termid}/vasset");
            // 当前媒资的ID
            $data['services']['unfavorite']['data'] = $results->vasseti_id;
        } else {
            $data['services']['favorite']['route'] = url("/{$spid}/ugc/favorite/{$termid}/vasset");
            $data['services']['favorite']['data']  = $results->vasseti_id;
        }
        $data['services']['back']['route'] = "";
        $data['services']['back']['data']  = "";
        $vcattagIds                        = DB::table('vasseti_vcattags')->where('vasseti_vcattags.vasseti_id', $vchanid)->pluck('vasseti_vcattags.vcattag_id')->toArray();
        $title                             = $results->title;
        $tags                              = $results->tags;
        $directors                         = $results->directors;
        // 推荐位数据 随机排序
        // $recommendVassetis = DB::table('vassetis')
        //     ->where('vassetis.vasseti_id', '<>', $results->vasseti_id)
        //     ->leftjoin('vasseti_vcattags','vasseti_vcattags.vasseti_id', '=', 'vassetis.vasseti_id')
        //     ->whereIn('vasseti_vcattags.vcattag_id',$vcattagIds)
        //     ->orWhere('title', 'like', '%' . $results->title . '%')
        //     ->orWhere('tags', 'like', '%' . $results->tags . '%')
        //     ->orWhere('directors', 'like', '%' . $results->directors . '%')
        //     ->orWhere('actors', 'like', '%' . $results->actors . '%')
        //     ->take(50)
        //     ->distinct()
        //     ->get();
        $recommendVassetis = DB::table('vassetis')
            ->where('vassetis.vasseti_id', '<>', $results->vasseti_id)
            ->where('vassetis.tags', 'like', '%' . $tags, '%')
            ->orderBy(\DB::raw('RAND()'))
            ->inRandomOrder()
            ->distinct()
            ->get();
        if ($recommendVassetis->first()) {
            foreach ($recommendVassetis as $key => $value) {
                $data['recommend'][$key]['rowid']    = $value->vasseti_id;
                $data['recommend'][$key]['vassetid'] = $value->vasseti_id;
                // 图片
                $recommendImg = json_decode($value->imgs, 1);
                if (empty($recommendImg)) {
                    $data['recommend'][$key]['img'] = (object) [];
                } else {
                    foreach ($recommendImg as $recommendKey => $recommendValue) {
                        $imgHref = image_match($recommendValue['href'], 'MIMG');
                        if ($imgHref) {
                            $data['recommend'][$key]['img'] = json_decode(json_encode(['href' => $ftpUrl . $imgHref]));
                            break;
                        } else {
                            $data['recommend'][$key]['img'] = (object) [];
                        }
                    }
                }
                $data['recommend'][$key]['title']                       = $value->title;
                $data['recommend'][$key]['subtitle']                    = $value->subtitle;
                $data['recommend'][$key]['onclick']['route']["tplType"] = "";
                $data['recommend'][$key]['onclick']['route']["tplID"]   = "";
                $data['recommend'][$key]['onclick']['href']             = url("/{$spid}/vasset/{$value->vasseti_id}/meta");
            }
        } else {
            $data['recommend'] = [];
        }
        return response()->json(['status' => '200', 'data' => $data]);
    }

}
